from django.test import TestCase
import os
if not os.environ.get("DJANGO_SETTINGS_MODULE"):
    os.environ.setdefault("DJANGO_SETTINGS_MODULE",'drf_demo.settings')

import django
django.setup()
# Create your tests here.
from rest_framework import serializers


class User(object):
    """用户类"""
    def __init__(self,name,age,gender):
        self.name = name
        self.age = age
        self.gender = gender

class UserSerializer(serializers.Serializer):
    # 字段 = serializers.字段类型（选项参数）
    name = serializers.CharField()
    age = serializers.IntegerField()
    gender = serializers.BooleanField()


if __name__ == '__main__':
    req_data = {
        'name':'ethan',
        'age':18,
        'gender':False
    }
    # 创建序列化器类UserSerializer的对象
    serializer = UserSerializer(data=req_data)

    # 调用is_valid进行数据校验
    res = serializer.is_valid() # True校验成功 False校验失败
    print(res)

    # 获取校验失败的错误信息,如果成功的话，返回一个空字典
    print(serializer.errors)

    # 获取校验之后的数据
    print(serializer.validated_data)


# if __name__ == '__main__':
#     # 创建User类的实例对象
#     user = User("ethanyan",16,False)
#
#     # {
#     #     'name':"ethanyan",
#     #     'age':16,
#     # }
#     # 创建序列化器类UserSerializer的对象
#     serializer = UserSerializer(user)
#     # 获取序列化之后的字典数据
#     res = serializer.data
#     print(res)